import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { MatDialog } from '@angular/material/dialog';
import { SelfDialogComponent } from '../../components/selfDialog/selfDialog.component';

@Injectable()
export class ResponseHandlerInterceptor implements HttpInterceptor {
    readonly dialog = inject(MatDialog);
    openDialog(msg: string, type: 'dialog' | 'toast' = 'dialog', success?: () => void, fail?: () => void): void {
        let data = {
            title: '提示',
            content: msg,
            showCancel: type !== 'toast',
            confirm: '确定',
            cancel: '取消',
            success: success,
            fail: fail
        }
        this.dialog.open(SelfDialogComponent, {
            width: '250px',
            enterAnimationDuration: 1,
            exitAnimationDuration: 1,
            data: data
        });
    }

    public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            filter((event: any) => {
                return event instanceof HttpResponse && event.status === 200
            }),
            map((event: HttpResponse<any>) => {
                const code = event.body.code;
                switch (code) {
                    case 200:
                        return event.clone({ body: event.body.data });
                    case 400: // Unauthorized
                        this.openDialog(event.body.msg || '请求失败', 'toast');
                        return event;
                    case 401: // Unauthorized
                        // todo
                        this.openDialog('登录失败', 'toast');
                        return event;
                    default:
                        // todo
                        return event;
                }
            })
        );
    }
}
